from django.db import models
from apps.UMM.models import User, CommissionCategory

# Create your models here.

class Customer(models.Model):
    """客户表"""
    CUSTOMER_SOURCE_CHOICES = [
        (0, 'Newbe工作室'),
        (1, '纽币德信息科技'),
        (2, '官方网站'),
        (3, '其它'),
    ]
    
    customer_name = models.CharField(max_length=255, verbose_name='客户名称', unique=True)
    customer_source = models.SmallIntegerField(choices=CUSTOMER_SOURCE_CHOICES, verbose_name='客户来源', null=True, blank=True)
    phone_number = models.CharField(max_length=20, verbose_name='手机号码', null=True, blank=True)
    
    class Meta:
        verbose_name = '客户'
        verbose_name_plural = '客户'
        
    def __str__(self):
        return self.customer_name

class Product(models.Model):
    """产品表"""
    product_name = models.CharField(max_length=50, verbose_name='产品名称')
    product_tag = models.CharField(max_length=50, verbose_name='产品标签')
    commission_category = models.ForeignKey(CommissionCategory, on_delete=models.CASCADE, verbose_name='提成分类')
    
    class Meta:
        verbose_name = '产品'
        verbose_name_plural = '产品'
        
    def __str__(self):
        return self.product_name

class Order(models.Model):
    """订单表"""
    ORDER_SOURCE_CHOICES = [
        (0, 'Newbe工作室'),
        (1, '纽币德信息科技'),
        (2, '官方网站'),
        (3, '其它'),
    ]
    
    PURCHASE_YEARS_CHOICES = [
        (0, '永久'),
        (1, '1年'),
        (2, '2年'),
        (3, '3年'),
        (4, '4年'),
        (5, '5年'),
    ]
    
    ORDER_STATUS_CHOICES = [
        (0, '未激活'),
        (1, '已激活'),
        (2, '临时IP激活')
    ]
    
    INVOICE_STATUS_CHOICES = [
        (0, '未开票'),
        (1, '已开票'),
    ]
    
    DOUBLE_COMMISSION_CHOICES = [
        (0, '否'),
        (1, '是'),
    ]
    
    order_source = models.SmallIntegerField(choices=ORDER_SOURCE_CHOICES, verbose_name='订单来源')
    order_number = models.CharField(max_length=255, verbose_name='订单号')
    customer_name = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='客户名称')
    order_date = models.DateField(verbose_name='下单日期')
    product_name = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='产品名称')
    order_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单金额')
    purchase_years = models.SmallIntegerField(choices=PURCHASE_YEARS_CHOICES, verbose_name='购买年限')
    order_status = models.SmallIntegerField(choices=ORDER_STATUS_CHOICES, verbose_name='订单状态')
    authorized_domain = models.CharField(max_length=255, verbose_name='授权域名', null=True, blank=True)
    activation_date = models.DateField(null=True, blank=True, verbose_name='激活日期')
    nickname = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='昵称')
    authorization_code = models.CharField(max_length=255, verbose_name='授权码')
    order_remarks = models.TextField(null=True, blank=True, verbose_name='订单备注')
    is_invoice = models.SmallIntegerField(choices=INVOICE_STATUS_CHOICES, default=0, verbose_name='是否已开票')
    creation_date = models.DateTimeField(auto_now_add=True, verbose_name='创建日期')
    last_modification_date = models.DateTimeField(auto_now=True, verbose_name='最后修改日期')
    commission = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='激活提成')
    is_double_coms = models.SmallIntegerField(choices=DOUBLE_COMMISSION_CHOICES, default=0, verbose_name='是否双倍提成')
    
    class Meta:
        verbose_name = '订单'
        verbose_name_plural = '订单'
        
    def __str__(self):
        return self.order_number
    
    def save(self, *args, **kwargs):
        """重写保存方法，自动计算提成"""
        # 订单状态为"已激活"或"临时IP激活"时计算提成
        if self.order_status == 1 or self.order_status == 2:  # 已激活 或 临时IP激活
            try:
                # 检查是否有激活人
                if self.nickname:
                    # 检查激活人是否参与提成计算
                    if self.nickname.is_commission_calc == 1:
                        # 获取产品的提成分类比例
                        product = self.product_name
                        if product and hasattr(product, 'commission_category'):
                            commission_ratio = product.commission_category.commission_ratio
                            
                            # 计算提成金额
                            self.commission = self.order_amount * commission_ratio
                            
                            # 如果是双倍提成，则将提成金额乘以2
                            if self.is_double_coms == 1:
                                self.commission *= 2
                                
                            # 输出调试信息
                            import logging
                            logger = logging.getLogger(__name__)
                            logger.info(f"订单 #{self.id} ({self.order_number}) 提成计算: 金额={self.order_amount} * 比例={commission_ratio} * 双倍倍数={2 if self.is_double_coms == 1 else 1} = {self.commission}, 订单状态={self.order_status}")
                    else:
                        # 激活人不参与提成计算，将提成设为0
                        self.commission = 0
                        import logging
                        logger = logging.getLogger(__name__)
                        logger.info(f"订单 #{self.id} ({self.order_number}) 的激活人 {self.nickname.nickname} 不参与提成计算，提成金额设为0")
            except Exception as e:
                # 记录异常但不中断保存流程
                import logging
                logger = logging.getLogger(__name__)
                logger.error(f"计算订单 #{self.id if self.id else '新订单'} ({self.order_number}) 的提成时出错: {str(e)}")
        
        # 执行原来的保存逻辑
        super().save(*args, **kwargs)

class Host_order(models.Model):
    """主机出租订单表"""
    ORDER_SOURCE_CHOICES = [
        (0, 'Newbe工作室'),
        (1, '纽币德信息科技'),
        (2, '官方网站'),
        (3, '其它'),
    ]
    
    order_number = models.CharField(max_length=20, verbose_name='订单号')
    rental_years = models.IntegerField(verbose_name='出租年限')
    order_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='订单金额')
    order_source = models.SmallIntegerField(choices=ORDER_SOURCE_CHOICES, verbose_name='订单来源')
    domain_name = models.CharField(max_length=100, verbose_name='网站域名')
    email = models.EmailField(max_length=100, verbose_name='电子邮箱', null=True, blank=True)
    mobile = models.CharField(max_length=20, verbose_name='手机号码', null=True, blank=True)
    customer_wechat = models.CharField(max_length=50, verbose_name='客户微信', null=True, blank=True)
    effective_date = models.DateField(verbose_name='生效日期')
    expiry_date = models.DateField(verbose_name='截至日期')
    order_remarks = models.TextField(verbose_name='订单备注', null=True, blank=True)
    commission = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='激活提成')

    # 添加关联字段
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='客户', null=True, blank=True)
    nickname = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='对接人')
    creation_date = models.DateTimeField(auto_now_add=True, verbose_name='创建日期')
    last_modification_date = models.DateTimeField(auto_now=True, verbose_name='最后修改日期')
    
    class Meta:
        verbose_name = '主机出租订单'
        verbose_name_plural = '主机出租订单'
        
    def __str__(self):
        return self.order_number

    def save(self, *args, **kwargs):
        """重写保存方法，自动计算提成"""
        try:
            # 检查是否有对接人及其是否参与提成计算
            if self.nickname and self.nickname.is_commission_calc == 1:
                # 导入CommissionCategory模型
                from apps.UMM.models import CommissionCategory
                
                # 查找"资源租赁"提成分类
                try:
                    resource_rental_category = CommissionCategory.objects.get(commission_category='资源租赁')
                    commission_ratio = resource_rental_category.commission_ratio
                    
                    # 计算提成金额
                    self.commission = self.order_amount * commission_ratio
                    
                    # 输出调试信息
                    import logging
                    logger = logging.getLogger(__name__)
                    logger.info(f"主机出租订单 #{self.id if self.id else '新订单'} ({self.order_number}) 提成计算: 金额={self.order_amount} * 比例={commission_ratio} = {self.commission}")
                    
                except CommissionCategory.DoesNotExist:
                    # 如果找不到资源租赁提成分类，记录日志
                    import logging
                    logger = logging.getLogger(__name__)
                    logger.error(f"计算主机出租订单提成失败: 未找到'资源租赁'提成分类")
                    # 不设置提成，保持原值
            elif self.nickname and self.nickname.is_commission_calc == 0:
                # 对接人不参与提成计算，将提成设为0
                self.commission = 0
                import logging
                logger = logging.getLogger(__name__)
                logger.info(f"主机出租订单 #{self.id if self.id else '新订单'} ({self.order_number}) 的对接人 {self.nickname.nickname} 不参与提成计算，提成金额设为0")
                
        except Exception as e:
            # 记录异常但不中断保存流程
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"计算主机出租订单 #{self.id if self.id else '新订单'} ({self.order_number}) 的提成时出错: {str(e)}")
        
        # 执行原来的保存逻辑
        super().save(*args, **kwargs)